﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iLangl.Model;

namespace iLangl.Customer.DAL.XMLStorage
{
	public class SettingsDAL : BaseStorageDAL, ISettingsDAL
	{
		public void AddWorkArea(WorkArea workarea, System.Data.IDbTransaction trans)
		{
			dtoXmlStorage.WorkAreaRow workAreaRow = Storage.WorkArea.FindById(workarea.Id);

			bool isNew = (workAreaRow == null);

			if (isNew)
			{
				workAreaRow = Storage.WorkArea.NewWorkAreaRow();
			}

			workAreaRow.Id = workarea.Id;
			workAreaRow.Name = workarea.Name;
			workAreaRow.ParentId = workarea.ParentId;

			if (isNew)
			{
				Storage.WorkArea.AddWorkAreaRow(workAreaRow);
			}

			if (trans == null)
			{
				AcceptChanges();
			}
		}

		public IList<WorkArea> ReadWorkAreas()
		{
			IList<WorkArea> result = new List<WorkArea>();
			foreach (dtoXmlStorage.WorkAreaRow workareaRow in Storage.WorkArea)
			{
				WorkArea wr = new WorkArea();
				wr.Id = workareaRow.Id;
				wr.Name = workareaRow.Name;
				if (!workareaRow.IsParentIdNull())
					workareaRow.ParentId = workareaRow.ParentId;

				result.Add(wr);
			}
			return result;
		}

		public void AddProduct(Model.Product product, System.Data.IDbTransaction trans)
		{
			dtoXmlStorage.ProductRow productRow = Storage.Product.FindById(product.Id);

			bool isNew = (productRow == null);

			if (isNew)
			{
				productRow = Storage.Product.NewProductRow();
			}

			productRow.Id = product.Id;
			productRow.Name = product.Name;
			productRow.Description = product.Description;

			if (isNew)
			{
				Storage.Product.AddProductRow(productRow);
			}

			if (trans == null)
			{
				AcceptChanges();
			}
		}

		public IList<Product> ReadProducts()
		{
			IList<Product> result = new List<Product>();
			foreach (dtoXmlStorage.ProductRow productRow in Storage.Product)
			{
				Product wr = new Product();
				wr.Id = productRow.Id;
				wr.Name = productRow.Name;

				result.Add(wr);
			}

			return result;
		}
	}
}
